<template>
    <view class="scale-container">
        <!-- 设备列表 -->
        <view v-if="!connectedDevice">
            <text>发现设备：</text>
            <view v-for="device in devices" :key="device.deviceId" class="device-item">
                <text>{{ device.name || 'Unknown' }} (信号:{{ device.RSSI }})</text>
                <button @tap="connectDevice(device.deviceId)">连接</button>
            </view>
            <button @tap="startScan" :disabled="scanning">重新扫描</button>
        </view>

        <!-- 称重显示 -->
        <view v-else>
            <text>当前重量：{{ weight }}</text>
            <button @tap="disconnectDevice">断开连接</button>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            devices: [], // 设备列表
            connectedDevice: null, // 已连接设备
            weight: '0.00kg', // 称重数据
            scanning: false, // 是否正在扫描
        };
    },
    methods: {
        // 初始化蓝牙
        initBluetooth() {
            uni.openBluetoothAdapter({
                success: () => this.startScan(),
                fail: (err) => uni.showToast({ title: '蓝牙初始化失败', icon: 'none' }),
            });
        },

        // 开始扫描设备
        startScan() {
            this.devices = [];
            this.scanning = true;
            uni.startBluetoothDevicesDiscovery({
                allowDuplicatesKey: true,
                success: () => {
                    uni.onBluetoothDeviceFound((res) => {
                        const newDevices = res.devices
                            .filter(device => device.name && device.name.match(/scale|weigh|ws-/i)) // 过滤电子秤设备
                            .map(device => ({
                                name: device.name,
                                deviceId: device.deviceId,
                                RSSI: device.RSSI,
                            }));
                        this.devices = [...new Set([...this.devices, ...newDevices])]; // 去重
                    });
                },
                fail: (err) => uni.showToast({ title: '扫描失败', icon: 'none' }),
            });
        },

        // 连接设备
        connectDevice(deviceId) {
            uni.createBLEConnection({
                deviceId,
                success: () => {
                    this.connectedDevice = deviceId;
                    this.scanning = false;
                    this.scanServices(deviceId);
                },
                fail: (err) => uni.showToast({ title: '连接失败', icon: 'none' }),
            });
        },

        // 扫描服务
        scanServices(deviceId) {
            uni.getBLEDeviceServices({
                deviceId,
                success: (res) => {
                    res.services.forEach(service => {
                        if (service.isPrimary) {
                            this.scanCharacteristics(deviceId, service.uuid);
                        }
                    });
                },
            });
        },

        // 扫描特征值
        scanCharacteristics(deviceId, serviceId) {
            uni.getBLEDeviceCharacteristics({
                deviceId,
                serviceId,
                success: (res) => {
                    res.characteristics.forEach(char => {
                        if (char.properties.notify) {
                            this.subscribeNotify(deviceId, serviceId, char.uuid);
                        }
                    });
                },
            });
        },

        // 订阅特征值通知
        subscribeNotify(deviceId, serviceId, charId) {
            uni.notifyBLECharacteristicValueChange({
                deviceId,
                serviceId,
                characteristicId: charId,
                state: true,
                success: () => {
                    uni.onBLECharacteristicValueChange((res) => {
                        const weight = this.parseWeightData(res.value);
                        if (weight !== null) {
                            this.weight = weight + 'kg';
                        }
                    });
                },
            });
        },

        // 断开连接
        disconnectDevice() {
            if (this.connectedDevice) {
                uni.closeBLEConnection({
                    deviceId: this.connectedDevice,
                    success: () => {
                        this.connectedDevice = null;
                        this.weight = '0.00kg';
                    },
                });
            }
        },

        // 解析称重数据
        parseWeightData(buffer) {
            const view = new DataView(buffer);
            // 尝试不同数据格式
            if (buffer.byteLength === 2) {
                return (view.getUint16(0, true) / 100).toFixed(2); // 2字节小端
            } else if (buffer.byteLength === 4) {
                return view.getFloat32(0, true).toFixed(2); // 4字节浮点
            }
            return null; // 无法解析
        },
    },
    mounted() {
        this.initBluetooth();
    },
    beforeDestroy() {
        this.disconnectDevice();
        uni.closeBluetoothAdapter();
    },
};
</script>

<style scoped>
.scale-container {
    padding: 20px;
}

.device-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}
</style>